/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.beanvalidator.BeanValidators;
import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.utils.DateUtils;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.utils.excel.ExportExcel;
import cn.net.ecode.common.utils.excel.ImportExcel;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Company;
import cn.net.ecode.modules.sys.entity.Employee;
import cn.net.ecode.modules.sys.entity.Office;
import cn.net.ecode.modules.sys.entity.Role;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.service.CompanyService;
import cn.net.ecode.modules.sys.service.OfficeService;
import cn.net.ecode.modules.sys.service.RoleService;
import cn.net.ecode.modules.sys.service.UserService;
import cn.net.ecode.modules.sys.utils.UserUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 用户Controller
 * @author ThinkGem/jiaoanjian
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private OfficeService officeService;

	@ModelAttribute
	public User get(String userCode, boolean isNewRecord) {
		return userService.get(userCode, isNewRecord);
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"list", ""})
	public String list(User user, Model model) {
		return "modules/sys/userList";
	}

	//@RequiresPermissions("sys:user:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response) {
		Page<User> page = null;
		user.setUserType(User.USER_TYPE_EMPLOYEE); 	// 员工
		user.setMgrType(User.MGR_TYPE_NOT_ADMIN);	// 非管理员
		user.getEmployee().getOffice().setIsQueryChildren(true);
		user.getEmployee().getCompany().setIsQueryChildren(true);
		if(user.isAll()){
			page = userService.findAllPage(new Page<User>(request, response), user);
		}else{
			page = userService.findPage(new Page<User>(request, response), user);
		}
		return page;
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user, HttpServletRequest request, Model model) {
		
		String op = request.getParameter("op");
		
		// 获取当前编辑用的角色和权限
		if(op.equals("authorize")) {
			user.setRoleList(userService.findUserRoleList(user));
			user.setUserDataScopeList(userService.findUserDataScopeList(user));
		}

		// 新增用户时，设置默认选择的角色
		if(user.getIsNewRecord()){
			String roleCodes = Global.getConfig("sys.user.defaultSetRoleCodes");
			if (roleCodes != null){
				user.setRoleCodes(roleCodes);
			}
		}
		
		// 获取可分配的权限
		model.addAttribute("allRoles", roleService.findList(new Role()));
		model.addAttribute("allCompanys", companyService.findList(new Company()));
		model.addAttribute("allOffices", officeService.findList(new Office()));
		
		// 获取编辑用户引用类型数据
		UserUtils.loadRefObj(user);
		user.setEmployee((Employee)user.getRefObj());
		model.addAttribute("user", user);
		return "modules/sys/userForm";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(User user, HttpServletRequest request) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (User.isAdmin(user.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		// user.setCompany(new Office(request.getParameter("company.id")));
		// user.setOffice(new Office(request.getParameter("office.id")));
		// 如果新密码为空，则不更换密码
		//if (StringUtils.isNotBlank(user.getNewPassword())) {
		//	user.setPassword(UserService.entryptPassword(user.getNewPassword()));
		//}
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, user)) {
			return renderResult(Global.FALSE, message);
		}
//		if (!"true".equals(checkUserCode(user.getOldUserCode(), user.getUserCode()))) {
//			return renderResult(Global.FALSE, "保存用户'" + user.getUserName() + "'失败，登录名已存在");
//		}
//		// 角色数据有效性验证，过滤不在授权内的角色
//		List<Role> roleList = Lists.newArrayList();
//		List<String> roleIdList = user.getRoleIdList();
//		for (Role r : roleService.findAllRole()) {
//			if (roleIdList.contains(r.getId())) {
//				roleList.add(r);
//			}
//		}
//		user.setRoleList(roleList);
		String op = request.getParameter("op");
		// 用户授权操作
		if(op.equals("authorize")){
			userService.saveAuthorize(user);
		}
		// 编辑用户操作
		else if(op.equals("edit")){
			userService.editUser(user);
		}
		// 添加用户操作
		else if(op.equals("add")){
			user.setMgrType(User.MGR_TYPE_NOT_ADMIN); //非管理员
			userService.addUser(user);
		}
		// 如果修改的是当前用户，则清除当前用户缓存
		if (user.getUserCode().equals(UserUtils.getUser().getUserCode())) {
			UserUtils.clearCache();
		}
		return renderResult(Global.TRUE, "保存用户'" + user.getUserName() + "'成功");
	}
	
	/** 
	 * 按角色给用户授权
	 * @author jiangwenchao
	 * @param request
	 * @param user
	 * @param model
	 * @return String  
	 */
	@RequiresPermissions("sys:user:authorize")
	@RequestMapping(value = "roleAuth")
	public String roleAuth(HttpServletRequest request, User user, Model model) {
		List<User> userList = userService.findUserByRoleCode(user);
		Map<String, User> selectData = Maps.newHashMap();
		for (User e : userList) {
			selectData.put(e.getUserCode(), e);
		}
		Role role = new Role();
		if (user != null && user.getRoleCode() != null) {
			role = roleService.get(user.getRoleCode());
		}
		String mul = request.getParameter("mul");
		if (mul == null || mul == "") {
			mul = "true";
		}
		model.addAttribute("role", role);
		model.addAttribute("selectData", selectData);
		model.addAttribute("mul", mul);
		return "modules/sys/roleAuth";
	}
	
	@RequiresPermissions("sys:user:authorize")
	@RequestMapping(value = "saveRoleAuth")
	@ResponseBody
	public String saveRoleAuth(@RequestParam(required=false) String roleCode,@RequestParam(required=false) List<String> userCodes, HttpServletRequest request) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.saveRoleAuth(roleCode,userCodes);
		return renderResult(Global.TRUE, "给角色指定用户成功");
	}
	
//	@InitBinder("employee")
//	public void initBinderEmployee(WebDataBinder binder) {
//		binder.setFieldDefaultPrefix("user.");
//	}
	
	/**
	 * 停用用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:disable")
	@RequestMapping(value = "disable")
	public String disable(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		String message = "";
		if (UserUtils.getUser().getUserCode().equals(user.getUserCode())) {
			message = "停用用户失败, 不允许停用当前用户";
		} else {
			userService.disableUser(user);
			message = "停用用户成功";
		}
		return renderResult(Global.TRUE, message);
	}
	
	/**
	 * 启用用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:activate")
	@RequestMapping(value = "activate")
	public String activate(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.activateUser(user);
		return renderResult(Global.TRUE, "启用用户成功");
	}
	
	/**
	 * 冻结用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:freeze")
	@RequestMapping(value = "freeze")
	public String freeze(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.freezeUser(user);
		return renderResult(Global.TRUE, "冻结用户成功");
	}
	
	/**
	 * 解冻用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:unfreeze")
	@RequestMapping(value = "unfreeze")
	public String unfreeze(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.activateUser(user);
		return renderResult(Global.TRUE, "解冻用户成功");
	}
	
	/**
	 * 密码重置
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:resetpwd")
	@RequestMapping(value = "resetpwd")
	public String resetpwd(User user) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		userService.resetUserPassword(user);
		return renderResult(Global.TRUE, "重置用户密码成功");
	}

//	@RequiresPermissions("sys:user:edit")
//	@RequestMapping(value = "delete")
//	public String delete(User user, RedirectAttributes redirectAttributes) {
//		if (Global.isDemoMode()) {
//			return renderResult(Global.FALSE, "演示模式，不允许操作！");
//		}
//		if (UserUtils.getUser().getUserCode().equals(user.getUserCode())) {
//			return renderResult(Global.FALSE, "删除用户失败, 不允许删除当前用户");
//		}
//		if (User.isAdmin(user.getUserCode())) {
//			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
//		}
//		userService.delete(user);
//		return renderResult(Global.TRUE, "删除用户成功");
//	}

	/**
	 * 导出用户数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(User user, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			user.setUserType(User.USER_TYPE_EMPLOYEE); 	// 员工
			user.setMgrType(User.MGR_TYPE_NOT_ADMIN);	// 非管理员
			List<User> list = userService.findList(user);
			new ExportExcel("用户数据", User.class).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/?repage";
	}

	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<User> list = ei.getDataList(User.class);
			for (User user : list) {
				try {
					if ("true".equals(checkUserCode("", user.getUserCode()))) {
						user.setPassword(UserService.encryptPassword(Global.getConfig("user.initPassword")));
						BeanValidators.validateWithException(validator, user);
						user.setMgrType(User.MGR_TYPE_NOT_ADMIN); //非管理员
						userService.addUser(user);
						successNum++;
					} else {
						failureMsg.append("<br/>登录名 " + user.getUserCode()
								+ " 已存在; ");
						failureNum++;
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("<br/>登录名 " + user.getUserCode()
							+ " 导入失败：");
					List<String> messageList = BeanValidators
							.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList) {
						failureMsg.append(message + "; ");
						failureNum++;
					}
				} catch (Exception ex) {
					failureMsg.append("<br/>登录名 " + user.getUserCode()
							+ " 导入失败：" + ex.getMessage());
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户"
					+ failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据导入模板.xlsx";
			List<User> list = Lists.newArrayList();
			list.add(UserUtils.getUser());
			new ExportExcel("用户数据", User.class, 2).setDataList(list)
					.write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/?repage";
	}

	/**
	 * 验证登录名是否有效
	 * @param oldUserCode
	 * @param userCode
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkUserCode")
	public String checkUserCode(String oldUserCode, String userCode) {
		if (userCode != null && userCode.equals(oldUserCode)) {
			return "true";
		} else if (userCode != null && userService.get(userCode) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 用户信息显示及保存
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "info")
	public String info(User user, String oldPassword, String newPassword, String confirmNewPassword,
			String oldPwdQuestionAnswer, String oldPwdQuestionAnswer2, String oldPwdQuestionAnswer3,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if (Global.isDemoMode()) {
			model.addAttribute("message", "演示模式，不允许操作！");
			return "modules/sys/userInfo";
		}
		
		String qtype = request.getParameter("qtype");
		model.addAttribute("qtype", qtype);
		logger.debug("qtype:"+qtype);
		
		if ("0".equals(qtype) && StringUtils.isNotBlank(user.getUserName())) {
			currentUser.setUserName(user.getUserName());
			currentUser.setMobile(user.getMobile());
			currentUser.setPhone(user.getPhone());
			currentUser.setEmail(user.getEmail());
			currentUser.setRemarks(user.getRemarks());
			model.addAttribute("message", "用户信息保存成功");
			userService.updateUserInfo(currentUser);
		}
		else if("1".equals(qtype)){
			currentUser.setPhoto(user.getPhoto());
			model.addAttribute("message", "修改用户头像成功");
			userService.updateUserInfo(currentUser);
		}
		else if("2".equals(qtype) && StringUtils.isNotBlank(oldPassword)){
			if(!UserService.validatePassword(oldPassword, currentUser.getPassword())){
				model.addAttribute("message", "旧密码错误，请重新输入");
				return "modules/sys/userInfo";
			}
			if(!StringUtils.equals(newPassword, confirmNewPassword)){
				model.addAttribute("message", "新密码与确认新密码不同，请重新输入");
				return "modules/sys/userInfo";
			}
			model.addAttribute("message", "修改密码成功");
			userService.updatePassword(currentUser.getUserCode(), confirmNewPassword);
		}
		else if("3".equals(qtype)){
			boolean updateQuesstion = false;
			// 如果从未设置过
			if (StringUtils.isBlank(currentUser.getPwdQuestion()) 
					&& StringUtils.isBlank(currentUser.getPwdQuestion2()) 
					&& StringUtils.isBlank(currentUser.getPwdQuestion3())){
				updateQuesstion = true;
			}
			// 验证密保答案
			else if ((currentUser.getPwdQuestionAnswer() == null || currentUser.getPwdQuestionAnswer2() == null || currentUser.getPwdQuestionAnswer3() == null)
					|| StringUtils.equals(currentUser.getPwdQuestionAnswer(), oldPwdQuestionAnswer)
					&& StringUtils.equals(currentUser.getPwdQuestionAnswer2(), oldPwdQuestionAnswer2)
					&& StringUtils.equals(currentUser.getPwdQuestionAnswer3(), oldPwdQuestionAnswer3)) {
				updateQuesstion = true;
			}else{
				model.addAttribute("message", "密保问题与答案不匹配。");
				model.addAttribute("newUser", user);
				model.addAttribute("oldPwdQuestionAnswer", oldPwdQuestionAnswer);
				model.addAttribute("oldPwdQuestionAnswer2", oldPwdQuestionAnswer2);
				model.addAttribute("oldPwdQuestionAnswer3", oldPwdQuestionAnswer3);
			}
			// 保存密保答案
			if (updateQuesstion){
				currentUser.setPwdQuestion(user.getPwdQuestion());
				currentUser.setPwdQuestionAnswer(user.getPwdQuestionAnswer());
				currentUser.setPwdQuestion2(user.getPwdQuestion2());
				currentUser.setPwdQuestionAnswer2(user.getPwdQuestionAnswer2());
				currentUser.setPwdQuestion3(user.getPwdQuestion3());
				currentUser.setPwdQuestionAnswer3(user.getPwdQuestionAnswer3());
				model.addAttribute("message", "密保问题修改成功");
				userService.updateQuestion(currentUser);
			}
		}

		model.addAttribute("user", currentUser);
		
		return "modules/sys/userInfo";
	}

	/**
	 * 返回用户信息
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "infoData")
	public User infoData() {
		return UserUtils.getUser();
	}

	/**
	 * 修改个人用户密码
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword)
				&& StringUtils.isNotBlank(newPassword)) {
			if (Global.isDemoMode()) {
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/userModifyPwd";
			}
			if (UserService.validatePassword(oldPassword, user.getPassword())) {
				userService.updatePassword(user.getUserCode(), newPassword);
				model.addAttribute("message", "修改密码成功");
			} else {
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "userSelect")
	public String userSelect(HttpServletRequest request,User user, Model model) {
		model.addAttribute("selectData",request.getParameter("selectData")); // 指定默认选中的ID
		return "modules/sys/userSelect";
	}

	/**
	 * 根据机构查询用户树格式
	 * @param officeCode 机构Code
	 * @param isAll 是否显示所有用户（true：不进行权限过滤）
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String officeCode, Boolean isAll, String isShowCode) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		User user = new User();
		Employee employee = new Employee();
		employee.setOfficeCode(officeCode);
		employee.getOffice().setIsQueryChildren(false);
		user.setEmployee(employee);
		user.setStatus(User.STATUS_NORMAL);
		user.setUserType(User.USER_TYPE_EMPLOYEE); 	// 员工
		user.setMgrType(User.MGR_TYPE_NOT_ADMIN);	// 非管理员
		List<User> list;
		if (isAll != null && isAll) {
			list = userService.findAllList(user);
		}else{
			list = userService.findList(user);
		}
		for (int i = 0; i < list.size(); i++) {
			User e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", "u_" + e.getId());
			map.put("pId", officeCode);
			if ("true".equals(isShowCode) || "1".equals(isShowCode)){
				map.put("name", "(" + e.getLoginCode() + ")" + StringUtils.replace(e.getUserName(), " ", ""));
			}else if ("2".equals(isShowCode)){
				map.put("name", StringUtils.replace(e.getUserName(), " ", "") + "(" + e.getLoginCode() + ")");
			}else{
				map.put("name", StringUtils.replace(e.getUserName(), " ", ""));
			}
			mapList.add(map);
		}
		return mapList;
	}

	// @InitBinder
	// public void initBinder(WebDataBinder b) {
	// b.registerCustomEditor(List.class, "roleList", new
	// PropertyEditorSupport(){
	// @Autowired
	// private SystemService systemService;
	// @Override
	// public void setAsText(String text) throws IllegalArgumentException {
	// String[] ids = StringUtils.split(text, ",");
	// List<Role> roles = new ArrayList<Role>();
	// for (String id : ids) {
	// Role role = systemService.getRole(Long.valueOf(id));
	// roles.add(role);
	// }
	// setValue(roles);
	// }
	// @Override
	// public String getAsText() {
	// return Collections3.extractToString((List) getValue(), "id", ",");
	// }
	// });
	// }
	
	@ResponseBody
	@RequiresPermissions("user")
	@RequestMapping(value = "checkQuestion")
	public String checkQuestion(User user,HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if (Global.isDemoMode()) {
			model.addAttribute("message", "演示模式，不允许操作！");
			return "modules/sys/userInfo";
		}
		if (StringUtils.equals(currentUser.getPwdQuestionAnswer(),
				user.getPwdQuestionAnswer())
				&& StringUtils.equals(currentUser.getPwdQuestionAnswer2(),
						user.getPwdQuestionAnswer2())
				&& StringUtils.equals(currentUser.getPwdQuestionAnswer3(),
						user.getPwdQuestionAnswer3())) {
			return renderResult(Global.TRUE,"密保问题校验成功！");
		}
		return renderResult(Global.FALSE,"密保问题答案错误！");
	}
}
